#!/usr/bin/env python
# -*- coding: utf-8 -*-
# datetime: 10/12/2023 下午10:05
# Author: name
# File: environmet_api.py
# ide: PyCharm
# description:

from datetime import datetime
from typing import List

from fastapi import APIRouter, HTTPException, Query

from backend.app.models.environment_model import EnvironmentModel, EnvironmentOut, EnvironmentIn, EnvironmentPage
from backend.app.utils.response_tepmlate import ResponseCode

environment_router = APIRouter(prefix="/environment", tags=["环境管理"])


# 定义 API 路由
@environment_router.post("/add")
async def create_environment(environment: EnvironmentIn):
    select_environment = await EnvironmentModel.filter(name=environment.name).first()
    if select_environment:
        return ResponseCode(environment.name).response_409()
    await EnvironmentModel.create(
        name=environment.name,
        address=environment.address,
        username=environment.username,
        password=environment.password,
        description=environment.description,
        login_temp_id=environment.login_temp_id,
        created_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        updated_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    )
    return ResponseCode(f'环境:{environment.name}').response_add()


# 获取内置列表（分页查询）
@environment_router.get("/page", response_model=EnvironmentPage)
async def get_environment_page_list(
        page: int = Query(1, ge=1),
        size: int = Query(10, ge=1, le=100),
        name: str = Query(None, min_length=0)
):
    skip = (page - 1) * size
    query = EnvironmentModel.all()
    if name:
        query = query.filter(name__icontains=name)
    total = await query.count()
    environments = await query.offset(skip).limit(size).values()
    return EnvironmentPage(total=total, page_size=size, current_page=page, search_key=name, results=environments)


@environment_router.get("/list", response_model=List[EnvironmentOut])
async def read_environment_list():
    return await EnvironmentModel.all()


@environment_router.get("/{environment_id}", response_model=EnvironmentOut)
async def get_environment(environment_id: int):
    environment = await EnvironmentModel.filter(id=environment_id).first()
    if not environment:
        return ResponseCode(environment_id).response_404()
    return environment


@environment_router.put("/{environment_id}")
async def update_environment(environment_id: int, environment: EnvironmentIn):
    select_server = await EnvironmentModel.filter(id=environment_id).first()
    select_other_server = await EnvironmentModel.exclude(id=environment_id).filter(name=environment.name).first()
    if select_other_server:
        return ResponseCode(environment.name).response_exist()
    if not select_server:
        return ResponseCode(environment.name).response_404()
    await EnvironmentModel.filter(id=environment_id).update(
        name=environment.name,
        address=environment.address,
        username=environment.username,
        password=environment.password,
        login_temp_id=environment.login_temp_id,
        description=environment.description,
        updated_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    )
    updated_environment = await EnvironmentModel.filter(id=environment_id).first()
    if not updated_environment:
        return ResponseCode(environment.name).response_404()
    return ResponseCode(f'环境:{environment.name}').response_update_success()


@environment_router.delete("/{environment_id}")
async def delete_environment(environment_id: int):
    deleted_count = await EnvironmentModel.filter(id=environment_id).delete()
    if not deleted_count:
        return ResponseCode(environment_id).response_404()
    return ResponseCode(f"{environment_id}的环境").response_delete()
